﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using Newtonsoft.Json;

namespace GanoESB
{
    public class SoapClient : IClient
    {
        private string secretKey;
        private string busUrl;

        public SoapClient(string secretKey, string busUrl)
        {
            this.secretKey = secretKey;
            this.busUrl = busUrl;

            if (!busUrl.StartsWith("http"))
            {
                throw new Exception(busUrl);
            }
        }

        private IMessageBus GetMessageBus()
        {
            if (busUrl.StartsWith("http"))
            {
                Bindings bindings = new Bindings();

                return ChannelFactory<IMessageBus>.CreateChannel(bindings.HttpBinding, new EndpointAddress(busUrl));
            }

            return null;
        }

        public MessageResponse<TResponse> Execute<TSource, TResponse>(IMessage msg)
        {
            IMessageBus bus = GetMessageBus();
            try
            {
                MessageRequest req = new MessageRequest();

                Type msgType = typeof(TSource);
                req.MessageName = msg.Scope + "_" + msgType.Name;
                req.MessageJson = JsonConvert.SerializeObject(msg);

                MessageResponse resp = bus.Execute(secretKey, req);

                TResponse r = (TResponse)JsonConvert.DeserializeObject(resp.Result, typeof(TResponse));

                return new MessageResponse<TResponse>(resp.StateCode, resp.StateText, r);
            }
            catch
            {
                (bus as ICommunicationObject).Abort();
                throw;
            }
            finally
            {
                (bus as ICommunicationObject).Close();
            }
        }
    }
}
